package com.hhf.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhf.springboot.annotation.AuthCheck;
import com.hhf.springboot.common.BaseResponse;
import com.hhf.springboot.common.DataGroupByDateDTO;
import com.hhf.springboot.common.DeleteRequest;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.common.Result;
import com.hhf.springboot.constant.UserConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.model.dto.userSign.UserSignAddRequest;
import com.hhf.springboot.model.dto.userSign.UserSignEditRequest;
import com.hhf.springboot.model.dto.userSign.UserSignQueryRequest;
import com.hhf.springboot.model.dto.userSign.UserSignUpdateRequest;
import com.hhf.springboot.model.entity.UserSign;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.UserSignVO;
import com.hhf.springboot.service.UserSignService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户签到接口
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/userSign")
@Slf4j
public class UserSignController {

    @Resource
    private UserSignService userSignService;

    @Resource
    private UserService userService;

    /**
     * 用户签到
     *
     * @param userSignAddRequest
     * @param request
     * @return
     */
    @PostMapping("/sign")
    public BaseResponse<Long> sign(@RequestBody UserSignAddRequest userSignAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userSignAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        UserSign userSign = new UserSign();
        BeanUtils.copyProperties(userSignAddRequest, userSign);
        // 数据校验
        userSignService.validUserSign(userSign, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        userSign.setUserId(loginUser.getId());

        //判断今日是否已经签到
        UserSignQueryRequest userSignQueryRequest = new UserSignQueryRequest();
        BeanUtils.copyProperties(userSign, userSignQueryRequest);
        List<UserSign> userSignList = userSignService.list(userSignService.getQueryWrapper(userSignQueryRequest));
        //已经签到,返回
        if (!userSignList.isEmpty()){
            return Result.error(ErrorCode.OPERATION_ERROR,"今日已签到");
        }
        //未签到
        // 写入数据库
        boolean result = userSignService.save(userSign);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserSignId = userSign.getId();
        return Result.success(newUserSignId);
    }


    // region 增删改查

    /**
     * 创建用户签到
     *
     * @param userSignAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserSign(@RequestBody UserSignAddRequest userSignAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userSignAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        UserSign userSign = new UserSign();
        BeanUtils.copyProperties(userSignAddRequest, userSign);
        // 数据校验
        userSignService.validUserSign(userSign, true);

        // 写入数据库
        boolean result = userSignService.save(userSign);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserSignId = userSign.getId();
        return Result.success(newUserSignId);
    }

    /**
     * 删除用户签到
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserSign(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserSign oldUserSign = userSignService.getById(id);
        ThrowUtils.throwIf(oldUserSign == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserSign.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userSignService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新用户签到（仅管理员可用）
     *
     * @param userSignUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserSign(@RequestBody UserSignUpdateRequest userSignUpdateRequest) {
        if (userSignUpdateRequest == null || userSignUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // TODO 在此处将实体类和 DTO 进行转换
        UserSign userSign = new UserSign();
        BeanUtils.copyProperties(userSignUpdateRequest, userSign);
        // 数据校验
        userSignService.validUserSign(userSign, false);
        // 判断是否存在
        long id = userSignUpdateRequest.getId();
        UserSign oldUserSign = userSignService.getById(id);
        ThrowUtils.throwIf(oldUserSign == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userSignService.updateById(userSign);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取用户签到（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserSignVO> getUserSignVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserSign userSign = userSignService.getById(id);
        ThrowUtils.throwIf(userSign == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(userSignService.getUserSignVO(userSign, request));
    }

    /**
     * 分页获取用户签到列表（仅管理员可用）
     *
     * @param userSignQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserSign>> listUserSignByPage(@RequestBody UserSignQueryRequest userSignQueryRequest) {
        long current = userSignQueryRequest.getCurrent();
        long size = userSignQueryRequest.getPageSize();
        // 查询数据库
        Page<UserSign> userSignPage = userSignService.page(new Page<>(current, size),
                userSignService.getQueryWrapper(userSignQueryRequest));
        return Result.success(userSignPage);
    }

    /**
     * 分页获取用户签到列表（封装类）
     *
     * @param userSignQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserSignVO>> listUserSignVOByPage(@RequestBody UserSignQueryRequest userSignQueryRequest,
                                                               HttpServletRequest request) {
        long current = userSignQueryRequest.getCurrent();
        long size = userSignQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserSign> userSignPage = userSignService.page(new Page<>(current, size),
                userSignService.getQueryWrapper(userSignQueryRequest));
        // 获取封装类
        return Result.success(userSignService.getUserSignVOPage(userSignPage, request));
    }

    /**
     * 分页获取当前登录用户创建的用户签到列表
     *
     * @param userSignQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserSignVO>> listMyUserSignVOByPage(@RequestBody UserSignQueryRequest userSignQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(userSignQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userSignQueryRequest.setUserId(loginUser.getId());
        long current = userSignQueryRequest.getCurrent();
        long size = userSignQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserSign> userSignPage = userSignService.page(new Page<>(current, size),
                userSignService.getQueryWrapper(userSignQueryRequest));
        // 获取封装类
        return Result.success(userSignService.getUserSignVOPage(userSignPage, request));
    }

    /**
     * 编辑用户签到（给用户使用）
     *
     * @param userSignEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserSign(@RequestBody UserSignEditRequest userSignEditRequest, HttpServletRequest request) {
        if (userSignEditRequest == null || userSignEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // TODO 在此处将实体类和 DTO 进行转换
        UserSign userSign = new UserSign();
        BeanUtils.copyProperties(userSignEditRequest, userSign);
        // 数据校验
        userSignService.validUserSign(userSign, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = userSignEditRequest.getId();
        UserSign oldUserSign = userSignService.getById(id);
        ThrowUtils.throwIf(oldUserSign == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldUserSign.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userSignService.updateById(userSign);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计用户签到
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedUserSign() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> userSignDataList = userSignService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(userSignDataList);

    }

    // endregion
}
